from flask import (
    Blueprint, render_template, request, redirect,
    url_for, flash, session, current_app
)
from .models import User, db

auth_bp = Blueprint('auth', __name__, template_folder='../templates')

@auth_bp.route('/', methods=['GET', 'POST'])
@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        uname = request.form['username']
        pwd   = request.form['password']
        remember = 'remember' in request.form  # checkbox 有勾则为 True

        user = User.query.filter_by(username=uname).first()
        if user and user.check_password(pwd):
            session.permanent = remember
            session['user_id'] = user.id
            return redirect(url_for('main.timeline'))
        flash('用户名或密码错误', 'danger')
    return render_template('login.html')

@auth_bp.route('/logout')
def logout():
    session.pop('user_id', None)
    return redirect(url_for('auth.login'))
